<template>
  <div class="hosts-page">
    <div class="page-header">
      <h2>主机管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加主机
        </el-button>
        <el-button type="success" @click="batchCollectInfo" :loading="collectingAll">
          <el-icon><Refresh /></el-icon>
          批量收集信息
        </el-button>
        <el-tag
          :type="monitoringActive ? 'success' : 'danger'"
          size="large"
          style="margin-left: 10px; padding: 8px 16px;"
        >
          <el-icon><Monitor /></el-icon>
          {{ monitoringActive ? `实时监控运行中 (${workerCount} Workers)` : '实时监控未运行' }}
        </el-tag>
        <el-button type="info" @click="exportToExcel" :loading="exporting">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
        <el-button type="warning" @click="triggerImportFile">
          <el-icon><Upload /></el-icon>
          导入Excel
        </el-button>
        <el-button type="default" @click="downloadTemplate">
          <el-icon><Document /></el-icon>
          保存模板
        </el-button>
        <!-- 隐藏的文件输入框 -->
        <input
          ref="fileInput"
          type="file"
          accept=".xlsx,.xls"
          style="display: none"
          @change="handleFileImport"
        />
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <!-- 取反筛选状态提示 -->
      <el-alert
        v-if="searchForm.invertFilter"
        title="问题主机筛选模式"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom: 16px;"
      >
        <template #default>
          当前显示所有非在线状态的主机（离线、检测中、异常、维护中等），已隐藏在线主机。
          <el-button
            type="text"
            size="small"
            @click="searchForm.invertFilter = false; searchHosts()"
            style="margin-left: 8px;"
          >
            切换到正常模式
          </el-button>
        </template>
      </el-alert>

      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input
            v-model="searchForm.search"
            placeholder="搜索主机名、IP地址、操作系统等..."
            clearable
            style="width: 300px;"
            @keyup.enter="searchHosts"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="异常" value="error" />
            <el-option label="检测中" value="checking" />
          </el-select>
        </el-form-item>
        <el-form-item label="筛选模式">
          <el-switch
            v-model="searchForm.invertFilter"
            active-text="问题主机"
            inactive-text="正常筛选"
            active-color="#f56c6c"
            inactive-color="#409eff"
            @change="searchHosts"
          />
          <el-tooltip
            content="启用后显示所有非在线状态的主机（离线、检测中、异常、维护中等），快速查看需要关注的问题主机"
            placement="top"
            style="margin-left: 8px;"
          >
            <el-icon
              :color="searchForm.invertFilter ? '#f56c6c' : '#909399'"
              style="cursor: help;"
            >
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHosts">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 主机列表 -->
    <el-card>
      <div class="table-header">
        <el-button
          type="danger"
          :disabled="selectedHosts.length === 0"
          @click="batchDeleteHosts"
          style="margin-bottom: 10px;"
        >
          <el-icon><Delete /></el-icon>
          批量删除 ({{ selectedHosts.length }})
        </el-button>
      </div>
      <el-table
        :data="hosts"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hostname" label="主机名" width="120" />
        <el-table-column prop="public_ip" label="公网IP" width="130">
          <template #default="{ row }">
            {{ row.public_ip || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="ip_address" label="内网IP" width="130" />
        <el-table-column prop="host_type_name" label="主机类型" width="100" />
        <el-table-column prop="environment_name" label="环境类型" width="100" />
        <el-table-column label="主机组" width="120">
          <template #default="{ row }">
            <span v-if="row.host_groups_names && row.host_groups_names.length > 0">
              {{ row.host_groups_names.join(', ') }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="os_type" label="操作系统类型" width="120">
          <template #default="{ row }">
            {{ row.os_type || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="os_version" label="操作系统版本" width="140">
          <template #default="{ row }">
            {{ row.os_version || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="cpu_cores" label="CPU核心数" width="100">
          <template #default="{ row }">
            {{ row.cpu_cores || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="cpu_architecture" label="CPU架构" width="100">
          <template #default="{ row }">
            {{ row.cpu_architecture || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="内存信息" width="120">
          <template #default="{ row }">
            {{ row.memory_display || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="磁盘信息" width="120">
          <template #default="{ row }">
            {{ row.disk_display || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="测试连接" placement="top">
              <el-button size="small" circle @click="testConnection(row)">
                <el-icon><Connection /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="收集信息" placement="top">
              <el-button size="small" type="success" circle @click="collectHostInfo(row)" :loading="row.collecting">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="SSH终端" placement="top">
              <el-button size="small" type="primary" circle @click="openSSHTerminal(row)">
                <el-icon><Monitor /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button size="small" type="warning" circle @click="editHost(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" type="danger" circle @click="deleteHost(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadHosts"
          @current-change="loadHosts"
        />
      </div>
    </el-card>

    <!-- 添加/编辑主机对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingHost ? '编辑主机' : '添加主机'"
      width="600px"
    >
      <el-form :model="hostForm" :rules="hostRules" ref="hostFormRef" label-width="100px">
        <el-form-item label="主机名" prop="hostname">
          <el-input v-model="hostForm.hostname" />
        </el-form-item>
        <el-form-item label="内网IP" prop="ip_address">
          <el-input v-model="hostForm.ip_address" />
        </el-form-item>
        <el-form-item label="公网IP">
          <el-input v-model="hostForm.public_ip" placeholder="可选" />
        </el-form-item>
        <el-form-item label="SSH端口" prop="ssh_port">
          <el-input-number v-model="hostForm.ssh_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="SSH用户" prop="ssh_username">
          <el-input v-model="hostForm.ssh_username" />
        </el-form-item>
        <el-form-item label="SSH密码" prop="ssh_password">
          <el-input v-model="hostForm.ssh_password" type="password" show-password />
        </el-form-item>
        <el-form-item label="环境" prop="environment">
          <el-select v-model="hostForm.environment" placeholder="请选择环境">
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主机类型" prop="host_type">
          <el-select v-model="hostForm.host_type" placeholder="请选择主机类型">
            <el-option
              v-for="type in hostTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <!-- 系统信息 -->
        <el-divider content-position="left">系统信息</el-divider>
        <el-form-item label="操作系统类型">
          <el-input v-model="hostForm.os_type" placeholder="如: Linux, Windows" />
        </el-form-item>
        <el-form-item label="操作系统版本">
          <el-input v-model="hostForm.os_version" placeholder="如: Ubuntu 20.04" />
        </el-form-item>
        <el-form-item label="CPU核心数">
          <el-input-number v-model="hostForm.cpu_cores" :min="1" />
        </el-form-item>
        <el-form-item label="CPU架构">
          <el-input v-model="hostForm.cpu_architecture" placeholder="如: x86_64, arm64" />
        </el-form-item>
        <el-form-item label="内存信息">
          <el-input v-model="hostForm.memory_info" placeholder="如: 16GB DDR4" />
        </el-form-item>
        <el-form-item label="磁盘信息">
          <el-input v-model="hostForm.disk_info" placeholder="如: 500GB SSD" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="hostForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveHost" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Connection, Monitor, Edit, Delete, Refresh, Download, Upload, Document, QuestionFilled } from '@element-plus/icons-vue'
import { cmdbAPI } from '../../api/cmdb'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const showAddDialog = ref(false)
const editingHost = ref(null)
const hostFormRef = ref()
const collectingAll = ref(false)
const exporting = ref(false)
const monitoringActive = ref(false)
const workerCount = ref(0)
const fileInput = ref()

const hosts = ref([])
const environments = ref([])
const hostTypes = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const selectedHosts = ref([])

const searchForm = reactive({
  search: '',
  status: '',
  invertFilter: false  // 取反筛选开关
})

const hostForm = reactive({
  hostname: '',
  ip_address: '',
  public_ip: '',
  private_ip: '',
  ssh_port: 22,
  ssh_username: '',
  ssh_password: '',
  environment: '',
  host_type: '',
  os_type: '',
  os_version: '',
  cpu_cores: null,
  cpu_architecture: '',
  memory_info: '',
  disk_info: '',
  description: ''
})

const hostRules = {
  hostname: [{ required: true, message: '请输入主机名', trigger: 'blur' }],
  ip_address: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  ssh_username: [{ required: true, message: '请输入SSH用户', trigger: 'blur' }],
  ssh_password: [{ required: true, message: '请输入SSH密码', trigger: 'blur' }],
  environment: [{ required: true, message: '请选择环境', trigger: 'change' }],
  host_type: [{ required: true, message: '请选择主机类型', trigger: 'change' }]
}

const getStatusType = (status) => {
  const types = {
    online: 'success',
    offline: 'info',
    maintenance: 'warning',
    error: 'danger',
    checking: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护中',
    'error': '异常',
    'checking': '检测中'
  }
  return statusMap[status] || status
}

const loadHosts = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
    }

    // 添加搜索参数
    if (searchForm.search) {
      // 通用搜索，后端需要支持多字段模糊匹配
      params.search = searchForm.search
    }

    // 处理状态筛选和取反筛选
    if (searchForm.invertFilter) {
      // 取反筛选：显示所有非在线状态的主机
      params.invert_filter = true
      // 如果同时选择了具体状态，则在非在线主机中进一步筛选
      if (searchForm.status && searchForm.status !== 'online') {
        params.status = searchForm.status
      }
    } else {
      // 正常筛选
      if (searchForm.status) {
        params.status = searchForm.status
      }
    }

    const response = await cmdbAPI.getHosts(params)
    hosts.value = response.results || response
    total.value = response.count || hosts.value.length
  } catch (error) {
    console.error('加载主机列表失败:', error)
  } finally {
    loading.value = false
  }
}

const searchHosts = () => {
  currentPage.value = 1 // 重置到第一页
  loadHosts()
}

const resetSearch = () => {
  searchForm.search = ''
  searchForm.status = ''
  searchForm.invertFilter = false
  currentPage.value = 1
  loadHosts()
}

// 定时刷新主机状态
let statusRefreshInterval = null
let statusWebSocket = null

const startStatusRefresh = () => {
  // 每60秒刷新一次状态（降低频率，因为有实时更新）
  statusRefreshInterval = setInterval(() => {
    loadHosts()
  }, 60000)

  // 启动WebSocket实时状态更新
  startStatusWebSocket()
}

const stopStatusRefresh = () => {
  if (statusRefreshInterval) {
    clearInterval(statusRefreshInterval)
    statusRefreshInterval = null
  }

  // 关闭WebSocket连接
  if (statusWebSocket) {
    statusWebSocket.close()
    statusWebSocket = null
  }
}

const startStatusWebSocket = () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) return

    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${wsProtocol}//${window.location.host}/ws/host-status/?token=${token}`

    statusWebSocket = new WebSocket(wsUrl)

    statusWebSocket.onopen = () => {
      console.log('主机状态WebSocket连接已建立')
    }

    statusWebSocket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        handleHostStatusUpdate(data)
      } catch (error) {
        console.error('解析主机状态更新消息失败:', error)
      }
    }

    statusWebSocket.onclose = (event) => {
      console.log('主机状态WebSocket连接已关闭')

      // 如果不是主动关闭，尝试重连
      if (event.code !== 1000) {
        setTimeout(() => {
          console.log('尝试重连主机状态WebSocket...')
          startStatusWebSocket()
        }, 5000)
      }
    }

    statusWebSocket.onerror = (error) => {
      console.error('主机状态WebSocket错误:', error)
    }

  } catch (error) {
    console.error('启动主机状态WebSocket失败:', error)
  }
}

const handleHostStatusUpdate = (data) => {
  if (data.type === 'host_status_update') {
    const { host_id, status, last_check_time } = data

    // 在主机列表中找到对应的主机并更新状态
    const hostIndex = hosts.value.findIndex(host => host.id === host_id)
    if (hostIndex !== -1) {
      const oldStatus = hosts.value[hostIndex].status
      hosts.value[hostIndex].status = status
      hosts.value[hostIndex].last_check_time = last_check_time

      console.log(`主机 ${hosts.value[hostIndex].hostname} 状态从 ${oldStatus} 更新为 ${status}`)

      // 可以在这里添加通知
      if (oldStatus !== status) {
        const statusText = getStatusText(status)
        ElMessage({
          message: `主机 ${hosts.value[hostIndex].hostname} 状态更新为: ${statusText}`,
          type: status === 'online' ? 'success' : status === 'offline' ? 'warning' : 'error',
          duration: 3000
        })
      }
    }
  }
}



const loadEnvironments = async () => {
  try {
    const response = await cmdbAPI.getEnvironments()
    environments.value = response.results || response
  } catch (error) {
    console.error('加载环境列表失败:', error)
  }
}

const loadHostTypes = async () => {
  try {
    const response = await cmdbAPI.getHostTypes()
    hostTypes.value = response.results || response
  } catch (error) {
    console.error('加载主机类型失败:', error)
  }
}


const testConnection = async (host) => {
  try {
    const response = await cmdbAPI.testConnection(host.id)
    if (response.success) {
      ElMessage.success('连接测试成功')
      loadHosts() // 刷新列表以更新状态
    } else {
      ElMessage.error(response.message || '连接测试失败')
    }
  } catch (error) {
    console.error('连接测试失败:', error)
  }
}

const collectHostInfo = async (host) => {
  try {
    // 设置单个主机的收集状态
    host.collecting = true

    const response = await cmdbAPI.collectHostInfo(host.id)
    if (response.success) {
      ElMessage.success(`主机 ${host.hostname} 信息收集成功`)
      // 刷新主机列表以显示最新信息
      loadHosts()
    } else {
      ElMessage.error(response.message || '信息收集失败')
    }
  } catch (error) {
    console.error('信息收集失败:', error)
    ElMessage.error('信息收集失败')
  } finally {
    host.collecting = false
  }
}

const batchCollectInfo = async () => {
  try {
    collectingAll.value = true
    ElMessage.info('开始批量收集主机信息...')

    const response = await cmdbAPI.batchCollectHostInfo()
    if (response.success) {
      ElMessage.success(response.message)
      // 刷新主机列表以显示最新信息
      loadHosts()
    } else {
      ElMessage.error(response.message || '批量收集失败')
    }
  } catch (error) {
    console.error('批量收集失败:', error)
    ElMessage.error('批量收集失败')
  } finally {
    collectingAll.value = false
  }
}



const checkMonitoringStatus = async () => {
  try {
    const response = await cmdbAPI.getMonitoringStatus()
    monitoringActive.value = response.monitoring_active
    workerCount.value = response.worker_count || 0

    if (!monitoringActive.value) {
      ElMessage.warning('实时监控服务未运行，主机状态将无法自动更新')
    }
  } catch (error) {
    console.error('获取监控状态失败:', error)
    monitoringActive.value = false
    workerCount.value = 0
  }
}

const openSSHTerminal = (host) => {
  router.push(`/cmdb/ssh-terminal/${host.id}`)
}

const editHost = (host) => {
  editingHost.value = host
  Object.assign(hostForm, {
    hostname: host.hostname,
    ip_address: host.ip_address,
    public_ip: host.public_ip || '',
    private_ip: host.private_ip || '',
    ssh_port: host.ssh_port,
    ssh_username: host.ssh_username,
    ssh_password: host.ssh_password,
    environment: host.environment,
    host_type: host.host_type,
    os_type: host.os_type || '',
    os_version: host.os_version || '',
    cpu_cores: host.cpu_cores || null,
    cpu_architecture: host.cpu_architecture || '',
    memory_info: host.memory_info || '',
    disk_info: host.disk_info || '',
    description: host.description
  })
  showAddDialog.value = true
}

const saveHost = async () => {
  if (!hostFormRef.value) return

  try {
    await hostFormRef.value.validate()
    saving.value = true

    // 清理数据，将空字符串转换为null
    const cleanedData = { ...hostForm }
    if (cleanedData.public_ip === '') {
      cleanedData.public_ip = null
    }
    if (cleanedData.private_ip === '') {
      cleanedData.private_ip = null
    }

    if (editingHost.value) {
      await cmdbAPI.updateHost(editingHost.value.id, cleanedData)
      ElMessage.success('主机更新成功')
    } else {
      await cmdbAPI.createHost(cleanedData)
      ElMessage.success('主机添加成功')
    }
    
    showAddDialog.value = false
    editingHost.value = null
    Object.assign(hostForm, {
      hostname: '',
      ip_address: '',
      public_ip: '',
      private_ip: '',
      ssh_port: 22,
      ssh_username: '',
      ssh_password: '',
      environment: '',
      host_type: '',
      os_type: '',
      os_version: '',
      cpu_cores: null,
      cpu_architecture: '',
      memory_info: '',
      disk_info: '',
      description: ''
    })
    loadHosts()
  } catch (error) {
    console.error('保存主机失败:', error)
    // 显示详细的错误信息
    if (error.response && error.response.data) {
      const errorData = error.response.data
      if (typeof errorData === 'object') {
        // 处理字段验证错误
        const errorMessages = []
        for (const [field, messages] of Object.entries(errorData)) {
          if (Array.isArray(messages)) {
            errorMessages.push(`${field}: ${messages.join(', ')}`)
          } else if (typeof messages === 'string') {
            errorMessages.push(`${field}: ${messages}`)
          }
        }
        if (errorMessages.length > 0) {
          ElMessage.error(`保存失败：${errorMessages.join('; ')}`)
        } else {
          ElMessage.error('保存主机失败，请检查输入信息')
        }
      } else if (typeof errorData === 'string') {
        ElMessage.error(`保存失败：${errorData}`)
      } else {
        ElMessage.error('保存主机失败，请检查输入信息')
      }
    } else if (error.message) {
      ElMessage.error(`保存失败：${error.message}`)
    } else {
      ElMessage.error('保存主机失败，请检查网络连接')
    }
  } finally {
    saving.value = false
  }
}

const deleteHost = async (host) => {
  try {
    await ElMessageBox.confirm(`确定要删除主机 ${host.hostname} 吗？`, '确认删除', {
      type: 'warning'
    })

    await cmdbAPI.deleteHost(host.id)
    ElMessage.success('主机删除成功')
    loadHosts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除主机失败:', error)
    }
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedHosts.value = selection
}

// 批量删除主机
const batchDeleteHosts = async () => {
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请选择要删除的主机')
    return
  }

  try {
    const hostNames = selectedHosts.value.map(host => host.hostname).join(', ')
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedHosts.value.length} 台主机吗？\n${hostNames}`,
      '批量删除确认',
      {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    // 使用批量删除API
    const hostIds = selectedHosts.value.map(host => host.id)
    await cmdbAPI.batchDeleteHosts(hostIds)

    ElMessage.success(`成功删除 ${selectedHosts.value.length} 台主机`)
    selectedHosts.value = []
    loadHosts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除主机失败:', error)
      ElMessage.error('批量删除失败，请重试')
    }
  }
}

// Excel导出功能
const exportToExcel = async () => {
  exporting.value = true
  try {
    // 获取当前页面的所有主机数据
    const exportData = hosts.value.map(host => ({
      '主机名': host.hostname,
      '公网IP': host.public_ip || '-',
      '内网IP': host.ip_address,
      '主机类型': host.host_type_name || '-',
      '环境类型': host.environment_name || '-',
      '主机组': host.host_groups_names ? host.host_groups_names.join(', ') : '-',
      '运行状态': getStatusText(host.status),
      '操作系统类型': host.os_type || '-',
      '操作系统版本': host.os_version || '-',
      'CPU核心数': host.cpu_cores || '-',
      'CPU架构': host.cpu_architecture || '-',
      '内存信息': host.memory_display || '-',
      '磁盘信息': host.disk_display || '-'
    }))

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 主机名
      { wch: 15 }, // 公网IP
      { wch: 15 }, // 内网IP
      { wch: 12 }, // 主机类型
      { wch: 12 }, // 环境类型
      { wch: 20 }, // 主机组
      { wch: 10 }, // 运行状态
      { wch: 12 }, // 操作系统类型
      { wch: 20 }, // 操作系统版本
      { wch: 10 }, // CPU核心数
      { wch: 10 }, // CPU架构
      { wch: 15 }, // 内存信息
      { wch: 20 }  // 磁盘信息
    ]
    ws['!cols'] = colWidths

    XLSX.utils.book_append_sheet(wb, ws, '主机列表')

    // 生成文件名
    const now = new Date()
    const timestamp = now.toISOString().slice(0, 19).replace(/[T:]/g, '_').replace(/-/g, '')
    const filename = `主机列表_${timestamp}.xlsx`

    // 导出文件
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([wbout], { type: 'application/octet-stream' })
    saveAs(blob, filename)

    ElMessage.success('Excel导出成功')
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage.error('导出Excel失败')
  } finally {
    exporting.value = false
  }
}

// 触发文件选择
const triggerImportFile = () => {
  fileInput.value.click()
}

// 处理文件导入
const handleFileImport = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  try {
    const data = await readExcelFile(file)
    await importHostsFromExcel(data)
    // 清空文件输入框
    event.target.value = ''
  } catch (error) {
    console.error('导入Excel失败:', error)
    ElMessage.error('导入Excel失败: ' + error.message)
  }
}

// 读取Excel文件
const readExcelFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        resolve(jsonData)
      } catch (error) {
        reject(error)
      }
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

// 从Excel数据导入主机
const importHostsFromExcel = async (data) => {
  if (!data || data.length === 0) {
    throw new Error('Excel文件为空或格式不正确')
  }

  // 过滤掉说明注释行（第一行数据通常是说明）
  const filteredData = data.filter(row => {
    // 如果第一个字段是说明文字，则跳过这一行
    const firstField = Object.values(row)[0]
    return firstField && !firstField.toString().includes('说明：')
  })

  if (filteredData.length === 0) {
    throw new Error('Excel文件中没有有效的主机数据')
  }

  // 定义必填字段（支持带*号和不带*号的格式）
  const requiredFieldMappings = {
    '主机名': ['主机名*', '主机名'],
    '内网IP': ['内网IP*', '内网IP'],
    'SSH端口': ['SSH端口*', 'SSH端口'],
    'SSH用户名': ['SSH用户名*', 'SSH用户名'],
    'SSH密码': ['SSH密码*', 'SSH密码'],
    '环境': ['环境*', '环境'],
    '主机类型': ['主机类型*', '主机类型']
  }

  // 检查必填字段是否存在
  const firstRow = filteredData[0]
  const availableFields = Object.keys(firstRow)
  const fieldMapping = {}

  for (const [standardField, possibleFields] of Object.entries(requiredFieldMappings)) {
    let foundField = null
    for (const possibleField of possibleFields) {
      if (availableFields.includes(possibleField)) {
        foundField = possibleField
        break
      }
    }
    if (!foundField) {
      throw new Error(`缺少必填字段: ${standardField}`)
    }
    fieldMapping[standardField] = foundField
  }

  // 可选字段映射
  const optionalFieldMappings = {
    '描述': ['描述'],
    '公网IP': ['公网IP'],
    '主机组': ['主机组']
  }

  for (const [standardField, possibleFields] of Object.entries(optionalFieldMappings)) {
    for (const possibleField of possibleFields) {
      if (availableFields.includes(possibleField)) {
        fieldMapping[standardField] = possibleField
        break
      }
    }
  }

  // 转换数据格式
  const hostsData = filteredData.map((row, index) => {
    // 验证必填字段值
    for (const [standardField, excelField] of Object.entries(fieldMapping)) {
      if (Object.keys(requiredFieldMappings).includes(standardField)) {
        if (!row[excelField] || row[excelField].toString().trim() === '') {
          throw new Error(`第${index + 2}行的${standardField}字段不能为空`)
        }
      }
    }

    return {
      hostname: row[fieldMapping['主机名']].toString().trim(),
      ip_address: row[fieldMapping['内网IP']].toString().trim(),
      ssh_port: parseInt(row[fieldMapping['SSH端口']]) || 22,
      ssh_username: row[fieldMapping['SSH用户名']].toString().trim(),
      ssh_password: row[fieldMapping['SSH密码']].toString().trim(),
      environment: row[fieldMapping['环境']].toString().trim(),
      host_type: row[fieldMapping['主机类型']].toString().trim(),
      description: fieldMapping['描述'] && row[fieldMapping['描述']] ?
        row[fieldMapping['描述']].toString().trim() : ''
    }
  })

  // 调用后端API批量导入
  const response = await cmdbAPI.batchImportHosts(hostsData)

  if (response.success) {
    ElMessage.success(`成功导入${response.imported_count}台主机`)
    loadHosts() // 刷新主机列表
  } else {
    throw new Error(response.message || '导入失败')
  }
}

// 下载Excel模板
const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()

  // 定义表头（与导出功能保持一致，必填字段添加*号）
  const headers = [
    '主机名*',      // 必填
    '公网IP',       // 可选（导出时有，导入时可选）
    '内网IP*',      // 必填
    '主机类型*',    // 必填
    '主机组',       // 可选
    '运行状态',     // 可选（系统自动设置）
    '操作系统类型', // 可选（系统自动收集）
    '操作系统版本', // 可选（系统自动收集）
    'CPU核心数',    // 可选（系统自动收集）
    'CPU架构',      // 可选（系统自动收集）
    '内存信息',     // 可选（系统自动收集）
    '磁盘信息',     // 可选（系统自动收集）
    'SSH端口*',     // 必填（导入专用字段）
    'SSH用户名*',   // 必填（导入专用字段）
    'SSH密码*',     // 必填（导入专用字段）
    '环境*',        // 必填（导入专用字段）
    '描述'          // 可选（导入专用字段）
  ]

  // 创建说明注释行
  const commentRow = [
    '说明：带*号的字段为必填项，其他字段为可选项。系统会自动收集操作系统、CPU、内存等信息。',
    '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''
  ]

  // 创建示例数据行
  const exampleRow = [
    'web01',                    // 主机名*
    '10.0.0.100',             // 公网IP
    '192.168.1.100',          // 内网IP*
    'Web服务器',              // 主机类型*
    '生产组',                 // 主机组
    '离线',                   // 运行状态
    'Linux',                  // 操作系统类型
    'CentOS Linux 7 (Core)',  // 操作系统版本
    '2',                      // CPU核心数
    'x86_64',                 // CPU架构
    '4.0 GB 总内存',          // 内存信息
    '总计: 50.0 GB',          // 磁盘信息
    '22',                     // SSH端口*
    'root',                   // SSH用户名*
    'password123',            // SSH密码
    '生产环境',               // 环境*
    '生产Web服务器'           // 描述
  ]

  // 手动创建工作表
  const ws = {}

  // 设置表头
  headers.forEach((header, index) => {
    const cellAddress = XLSX.utils.encode_cell({ r: 0, c: index })
    ws[cellAddress] = {
      v: header,
      t: 's',
      s: {
        font: {
          bold: true,
          color: { rgb: header.includes('*') ? 'FF0000' : '000000' }
        },
        alignment: { horizontal: 'center' },
        fill: { fgColor: { rgb: 'F2F2F2' } }
      }
    }
  })

  // 设置说明注释行
  commentRow.forEach((comment, index) => {
    const cellAddress = XLSX.utils.encode_cell({ r: 1, c: index })
    ws[cellAddress] = {
      v: comment,
      t: 's',
      s: {
        font: { italic: true, color: { rgb: '666666' } },
        fill: { fgColor: { rgb: 'FFFACD' } }
      }
    }
  })

  // 设置示例数据行
  exampleRow.forEach((example, index) => {
    const cellAddress = XLSX.utils.encode_cell({ r: 2, c: index })
    ws[cellAddress] = {
      v: example,
      t: typeof example === 'number' ? 'n' : 's'
    }
  })

  // 设置工作表范围
  ws['!ref'] = XLSX.utils.encode_range({
    s: { r: 0, c: 0 },
    e: { r: 2, c: headers.length - 1 }
  })

  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 主机名*
    { wch: 15 }, // 公网IP
    { wch: 15 }, // 内网IP*
    { wch: 12 }, // 主机类型*
    { wch: 20 }, // 主机组
    { wch: 10 }, // 运行状态
    { wch: 12 }, // 操作系统类型
    { wch: 20 }, // 操作系统版本
    { wch: 10 }, // CPU核心数
    { wch: 10 }, // CPU架构
    { wch: 15 }, // 内存信息
    { wch: 20 }, // 磁盘信息
    { wch: 10 }, // SSH端口*
    { wch: 12 }, // SSH用户名*
    { wch: 12 }, // SSH密码
    { wch: 12 }, // 环境*
    { wch: 20 }  // 描述
  ]
  ws['!cols'] = colWidths

  // 合并说明注释单元格（A2:Q2）
  ws['!merges'] = [
    { s: { r: 1, c: 0 }, e: { r: 1, c: headers.length - 1 } }
  ]

  XLSX.utils.book_append_sheet(wb, ws, '主机导入模板')

  // 导出模板文件
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/octet-stream' })
  saveAs(blob, '主机导入模板.xlsx')

  ElMessage.success('模板下载成功')
}

onMounted(() => {
  loadHosts()
  loadEnvironments()
  loadHostTypes()
  startStatusRefresh()
  checkMonitoringStatus()
})

onUnmounted(() => {
  stopStatusRefresh()
})
</script>

<style scoped>
.hosts-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 取反筛选样式 */
.el-switch.is-checked {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

/* 问题主机筛选提示 */
.el-form-item:has(.el-switch[aria-checked="true"]) {
  background: linear-gradient(90deg, #fef2f2, #fef7f7);
  border: 1px solid #fecaca;
  border-radius: 6px;
  padding: 8px 12px;
  margin: 4px 0;
}

/* 状态标签样式 */
.status-tag {
  font-weight: bold;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
</style>
